package com.helint.component.encryption.handler;

import com.alibaba.fastjson2.JSONObject;
import com.helint.component.encryption.prop.RsaProperties;
import com.helint.component.encryption.util.AESUtil;
import lombok.AllArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * 响应加解密拦截器
 *
 * @author junjunhuang
 * @version @version 1.0.0
 * @date 2024/01/25 11:55
 */
@Component
@AllArgsConstructor
@ControllerAdvice
public class EncryptionResponseHandler implements ResponseBodyAdvice<Object> {
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    private final RsaProperties properties;

    /**
     * 返回true，才会走beforeBodyWrite方法
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 判断是否开启
        return properties.getEnable();
    }

    /**
     * 响应加密
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse serverHttpResponse) {
        // 白名单
        if (checkUrls(properties.getIgnoreUrls(), request.getURI().getPath())) {
            return body;
        }

        // 拿到响应的数据
        String json = JSONObject.toJSONString(body);
        // 进行加密
        return AESUtil.encryptCBC(json, properties.getAesKey() );
    }

    public static void main(String[] args) {
        System.out.println(AESUtil.encryptCBC("userId=123456", "G99YPUMGNO78FG8W04LKXKUHMO89AUQ0" ));
    }
    /**
     * 对url进行校验匹配
     */
    private boolean checkUrls(List<String> urls, String path) {
        return urls.stream().anyMatch(url -> pathMatcher.match(url, path));
    }
}